/**
 * Created by Administrator on 2018/1/5.
 * ionic cordova plugin add phonegap-nfc
 * npm install --save @ionic-native/nfc
 *
 * 1.在使用该工具类时先通过以上命令安装NFC,
 * 2.在app.module.ts中的写入
 * import { NFC } from '@ionic-native/nfc';
 * 在providers中引入NFC
 * 最后在AppModule的构造函数中初始化 ZQHNFC.nfc = this.nfc;
 */
import { NFC } from '@ionic-native/nfc';

export class ZQHNFC{
  public static  nfc: NFC;

  constructor(){

  }

  /* 检查NFC是否在该设备上可用并启用 0:可用，1：不可用 */
  public static judgeEnabled(callBack){
    this.nfc.enabled().then(
      function () {
        callBack(0);
        console.log("NFC可以用");
      },
      function () {
        callBack(1);
        console.log("NFC不可以用");
      }
    );
  }

  /* 读取NfC的过程
  * 1.判断设备的NFC是否能用
  * 2.如果不能用则打开setting界面
  * 3.如果能用则开启监听
  * */
  public static readNFC(callBack){
    let readID: string = "";
    this.judgeEnabled(
      result => {
        if(result == 1){
          this.nfc.showSettings();
        }else{
          this.nfc.addTagDiscoveredListener(()=>{
              console.log('successfully');
            },(err) =>{
              console.log('error addTagDiscoveredListener', err);
            }
          ).subscribe(
            event =>{
              console.log('successfully addTagDiscoveredListener');
              readID = this.nfc.bytesToHexString(event.tag.id);
              callBack(readID);
            }
          );
        }
      }
    );
  }

}
